<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick" style="margin-left: 20px; margin-top: 10px; margin-right: 20px">
      <el-tab-pane label="基本信息" name="first">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="商品分类">
            <el-select v-model="form.goods.category1Id" placeholder="请选择一级分类">
              <el-option
                v-for="item in category1Array"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="form.goods.category2Id" placeholder="请选择二级分类">
              <el-option
                v-for="item in category2Array"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="form.goods.category3Id" placeholder="请选择三级分类">
              <el-option
                v-for="item in category3Array"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>

            <span style="margin-left: 20px" v-show="form.goods.typeTemplateId != null">模板ID:{{form.goods.typeTemplateId}}</span>

          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="form.goods.goodsName"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌">
            <el-select v-model="form.goods.brandId" placeholder="请选择品牌">
              <el-option
                v-for="item in brandArray"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="副标题">
            <el-input v-model="form.goods.caption"></el-input>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="form.goods.price">
              <template slot="prepend">¥</template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品简介" style="height: 240px">
            <editor style="height: 200px;" v-model="form.goodsDesc.introduction"></editor>
          </el-form-item>
          <el-form-item label="包装列表">
            <el-input type="textarea" v-model="form.goodsDesc.packageList"></el-input>
          </el-form-item>
          <el-form-item label="售后服务">
            <el-input type="textarea" v-model="form.goodsDesc.saleService"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="second">
        <el-button type="primary" @click="dialogVisible = true">上传图片</el-button>
        <el-table
          :data="imageData"
          border
          style="width: 100%">
          <el-table-column
            prop="color"
            label="颜色">
          </el-table-column>
          <el-table-column
            prop="url"
            label="图片">
            <template slot-scope="scope">
              <el-image :src="scope.row.url" style="width: 100px; height: 100px"></el-image>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="180">
            <template slot-scope="scope">
              <el-button type="danger" @click="removeImage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog
          title="上传图片"
          :visible.sync="dialogVisible"
          width="30%">

          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="颜色">
              <el-input v-model="imageObj.color"></el-input>
            </el-form-item>
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                action="/dev-api/goods/goods/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :headers="{'authorization':'Bearer '+getToken()}">
                <img v-if="imageObj.url" :src="imageObj.url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveImage">确 定</el-button>
          </span>
        </el-dialog>

      </el-tab-pane>
      <el-tab-pane label="拓展属性" name="third">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item :label="item.name" v-for="item in attributeItemsArray">
            <el-input v-model="item.value"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品规格" name="fourth">

        <el-form ref="form" :model="form" label-width="180px">
          <el-form-item :label="item.name" v-for="item in specOptionArray">
            <el-checkbox @change="selectOption(item.name, option.optionName)" v-for="option in item.tbSpecOptionList">{{option.optionName}}</el-checkbox>
          </el-form-item>
        </el-form>

        <el-table
          :data="sku"
          border
          style="width: 100%">

          <el-table-column
            v-for="spec in specificationItems"
            :label="spec.attributeName">

            <template slot-scope="scope">
              {{scope.row.spec[spec.attributeName]}}
            </template>
          </el-table-column>

          <el-table-column
            label="价格"
            width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存"
            width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.num"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-button @click="save">保存</el-button>

    {{sku}}

    <hr>

    {{form}}
  </div>
</template>
<script>
import { listCategory, getCategory } from "@/api/goods/category";
import { getTemplate } from "@/api/goods/template";
import { getSpec } from "@/api/goods/spec";

import { getToken } from "@/utils/auth";
import { addGoods } from "@/api/goods/goods";

export default {
  data() {
    return {
      activeName: 'first',
      form:{
        goods:{
          category1Id: null,
          category2Id: null,
          category3Id: null,
          goodsName: '',
          brandId: null,
          caption: '',
          price: 0,
          typeTemplateId: null
        },
        goodsDesc:{
          introduction: '',
          packageList:'',
          saleService:'',
          customAttributeItems: '',
          itemImages:'',
          specificationItems:''
        },
        item:[

        ]
      },
      category1Array:[],
      category2Array:[],
      category3Array:[],
      brandArray: [],
      attributeItemsArray: [],
      imageData:[],
      dialogVisible: false,
      imageObj:{
        color:'',
        url:''
      },
      specOptionArray:[],
      specificationItems:[],
      sku:[]
    };
  },
  created() {
    listCategory({parentId:0}).then((res)=>{
      this.category1Array = res.rows
    })
  },
  watch:{
    "form.goods.category1Id":function (newVal, oldVal) {
      this.form.goods.category2Id = null;
      this.form.goods.category3Id = null;

      this.category3Array = []

      listCategory({parentId:this.form.goods.category1Id}).then((res)=>{
        this.category2Array = res.rows
      })
    },
    "form.goods.category2Id":function (newVal, oldVal) {
      this.form.goods.category3Id = null;

      if(this.form.goods.category2Id != null){
        listCategory({parentId:this.form.goods.category2Id}).then((res)=>{
          this.category3Array = res.rows
        })
      }
    },
    "form.goods.category3Id":function (newVal, oldVal) {
      if(newVal == null){
        this.form.goods.typeTemplateId = null;
        return;
      }

      getCategory(this.form.goods.category3Id).then((res)=>{
        this.form.goods.typeTemplateId = res.data.typeId
      })
    },
    "form.goods.typeTemplateId":function (newVal, oldVal) {
      if(newVal == null){
        this.form.goods.brandId = null;
        this.brandArray = []
        this.specOptionArray = []
        this.attributeItemsArray = [];
        return;
      }

      getTemplate(this.form.goods.typeTemplateId).then((res)=>{
        var template = res.data;
        this.brandArray = JSON.parse(template.brandIds)
        this.attributeItemsArray = JSON.parse(template.attributeItems)
        var specArray = JSON.parse(template.specIds)
        for(var i in specArray){
          var spec = specArray[i]
          getSpec(spec.id).then((res)=>{
            this.specOptionArray.push(res.data)
          })
        }

      })
    }
  },
  methods: {
    getToken,
    handleClick(tab, event) {
      console.log(tab, event);
    },
    save(){
      this.form.goodsDesc.customAttributeItems =  JSON.stringify(this.attributeItemsArray)
      this.form.goodsDesc.itemImages = JSON.stringify(this.imageData)
      this.form.goodsDesc.specificationItems = JSON.stringify(this.specificationItems)

      var sku = JSON.parse(JSON.stringify(this.sku));
      for(var i in sku){
        var skuObj = sku[i];
        skuObj.spec = JSON.stringify(skuObj.spec)
      }
      this.form.item = sku;

      addGoods(this.form).then((res)=>{
        if(res.code==200){
          this.$message.success("商品发布成功")
        }else{
          this.$message.error(res.msg)
        }
      })


    },
    handleAvatarSuccess(res, file) {
      this.imageObj.url = res.msg;
    },
    saveImage(){
      this.imageData.push(this.imageObj)
      this.dialogVisible = false
      this.imageObj  = {
        color:'',
        url:''
      }
    },
    removeImage(row){
      var index = this.imageData.indexOf(row);
      this.imageData.splice(index, 1);
    },
    selectOption(specName, optionName){
      //this.$message.info(specName+"---"+optionName)
      if(this.specificationItems.length == 0){
        //第一次勾选
        var obj = {
          "attributeName": specName,
          "attributeValue": [optionName]
        }
        this.specificationItems.push(obj)
        this.initSKU();
        return;
      }

      //判断当前勾选的规格在数组中是否存在
      for(var i in this.specificationItems){
        var spec = this.specificationItems[i];
        if(specName == spec.attributeName){
          //当前点击的规格已经存在，判断当前点击的规格参数是否存在
          var index = spec.attributeValue.indexOf(optionName)
          if(index < 0){
            //当前点击的选项在数组中不存在
            spec.attributeValue.push(optionName)
          }else{
            //存在，需要取消选中
            spec.attributeValue.splice(index, 1);

            if(spec.attributeValue.length==0){
              this.specificationItems.splice(i,1)
            }
          }
          this.initSKU();
          return;
        }
      }

      //当前点击的规格在数组中不存
      var obj = {
        "attributeName": specName,
        "attributeValue": [optionName]
      }
      this.specificationItems.push(obj)
      this.initSKU();
      return;
    },
    initSKU(){
      var sku = [{spec:{}}];
      //  [{"attributeName":"电脑屏幕尺寸","attributeValue":["15 寸","16 寸"]},{"attributeName":"电脑CPU","attributeValue":["Core I7","Core I9"]}]
      for(var i in this.specificationItems){
        // {"attributeName":"电脑屏幕尺寸","attributeValue":["15 寸","16 寸"]}
        var specObj = this.specificationItems[i];
        var newSku = [];
        for(var j in sku) {
          var obj = sku[j];
          for (var k in specObj.attributeValue) {
            var option = specObj.attributeValue[k];
            var copeObj = JSON.parse(JSON.stringify(obj));
            copeObj.spec[specObj.attributeName] = option;
            newSku.push(copeObj)
          }
        }
        sku = newSku;
      }
      this.sku = sku;
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
